﻿using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace System
{
    /// <summary>
    /// Linq操作帮助类
    /// </summary>
    public static class LinqHelper
    {
        /// <summary>
        /// 创建初始条件为True的表达式
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static Expression<Func<T,bool>> True<T>()
        {
            return x => true;
        }

        /// <summary>
        /// 创建初始条件为False的表达式
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static Expression<Func<T, bool>> False<T>()
        {
            return x => false;
        }
        /// <summary>
        /// 泛型排序方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Sour">数据集</param>
        /// <param name="SortExpression">排序字段</param>
        /// <param name="Direction">排序方式 asc  desc</param>
        /// <returns></returns>
        public static IQueryable<T> OrderSort<T>(this IQueryable<T> Sour, string SortExpression, string Direction)
        {
            string SortDirection = string.Empty;
            if (Direction == "asc")
                SortDirection = "OrderBy";
            else if (Direction == "desc")
                SortDirection = "OrderByDescending";
            ParameterExpression pe = Expression.Parameter(typeof(T), SortExpression);
            PropertyInfo pi = typeof(T).GetProperty(SortExpression);
            Type[] types = new Type[2];
            types[0] = typeof(T);
            types[1] = pi.PropertyType;
            Expression expr = Expression.Call(typeof(Queryable), SortDirection, types, Sour.Expression, Expression.Lambda(Expression.Property(pe, SortExpression), pe));
            IQueryable<T> query = Sour.Provider.CreateQuery<T>(expr);
            return query;
        }
    }
}
